package entity;

import database.DatabaseHelper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class Course {

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Course(String id, String name) {
        this.id = id;
        this.name = name;
    }

    /* C */
    public static boolean create(DatabaseHelper db, String id, String name) throws SQLException {
        return db.update("insert into course(id,name) value (?,?)", id, name) > 0;
    }

    /* R */
    public static ArrayList<Course> findWhere(DatabaseHelper db, String condition, Object... params) throws SQLException {
        String query = "select id,name from course where " + condition;
        ResultSet rs = db.query(query, params);
        ArrayList<Course> courses = new ArrayList<>();
        while (rs.next()) {
            courses.add(new Course(rs.getString(1), rs.getString(2)));
        }
        rs.close();
        return courses;
    }

    public static Course find(DatabaseHelper db, String id) throws SQLException {
        ArrayList<Course> courses = findWhere(db, "id = ?", id);
        return courses.isEmpty() ? null : courses.get(0);
    }

    public static ArrayList<Course> findByName(DatabaseHelper db, String name) throws SQLException {
        return findWhere(db, "name = ?", name);
    }

    public static ArrayList<Course> findAll(DatabaseHelper db) throws SQLException {
        return findWhere(db, "true");
    }

    public ArrayList<Section> getSections(DatabaseHelper db) throws SQLException {
        return Section.findWhere(db, "cou_id = ?", id);
    }

    public boolean refresh(DatabaseHelper db) throws SQLException {
        Course cou = Course.find(db, id);
        if (cou == null)
            return false;
        this.name = cou.name;
        return true;
    }

    /* U */
    boolean setAttribute(DatabaseHelper db, String attribute, Object value) throws SQLException {
        String update = "update course set " + attribute + " = ? where id = ?";
        int affectedRows = db.update(update, value, id);
        refresh(db);
        return affectedRows > 0;
    }

    public boolean setName(DatabaseHelper db, String name) throws SQLException {
        return setAttribute(db, "name", name);
    }

    /* D */
    public boolean delete(DatabaseHelper db) throws SQLException {
        return db.update("delete from course where id = ?", id) > 0;
    }
}
